// pages/shangchuan/shangchuan.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 0 上传中  1 上传完成 2 上传失败
 
    thismuluid:"",
    // userId:2,
    jindulist:[],
    headImg:[],
    type:'',

    success:0,

    filemap: [
      { "txt": 1 },
      { "doc": 1 },
      { "docx": 1 },
      { "xls": 1 },
      { "xlsx": 1 },
      { "ppt": 1 },
      { "pptx": 1 },
      { "pdf": 1 },
      { "bmp": 2 },
      { "jpg": 2 },
      { "jpeg": 2 },
      { "png": 2 },
      { "tiff": 2 },
      { "gif": 2 },
      { "pcx": 2 },
      { "tga": 2 },
      { "exif": 2 },
      { "fpx": 2 },
      { "svg": 2 },
      { "psd": 2 },
      { "cdr": 2 },
      { "pcd": 2 },
      { "dxf": 2 },
      { "ufo": 2 },
      { "eps": 2 },
      { "ai": 2 },
      { "raw": 3 },
      { "wmf": 3 },
      { "mp4": 3 },
      { "avi": 3 },
      { "mov": 3 },
      { "wmv": 3 },
      { "navi": 3 },
      { "3gp": 3 },
      { "mkv": 3 },
      { "f4v": 3 },
      { "rmvb": 3 },
      { "webm": 3 },
      { "mp3": 4 },
      { "wma": 4 },
      { "wav": 4 },
      { "mod": 4 },
      { "ra": 4 },
      { "cd": 4 },
      { "md": 4 },
      { "asf": 4 },
      { "aac": 4 },
      { "ape": 4 },
      { "mid": 4 },
      { "ogg": 4 },
      { "m4a": 4 },
      { "vqf": 4 },
      { "rar": 5 },
      { "tar": 5 },
      { "zip": 5 },
      { "gzip": 5 },
      { "cab": 5 },
      { "uue": 5 },
      { "abj": 5 },
      { "bz2": 5 },
      { "lzh": 5 },
      { "jar": 5 },
      { "ace": 5 },
      { "iso": 5 },
      { "7-zip": 5 },
      { "z": 5 },
      { "htm": 5 },
      { "html": 5 },
      { "jsp": 5 },
    ],
  },

  // 上传多张
  uploadimg(data) {
    var that = this
    var i = data.i ? data.i : 0//当前上传的哪张图片
    var success = data.success ? data.success : 0 //上传成功的个数
    var fail = data.fail ? data.fail : 0 //上传失败的个数

    var obj = {}

    obj.index = i

    data.path[i].fileName = that.generateTimeReqestNumber() + '.' + data.path[i].fileFormat
    if (data.path[i].name){
      that.setData({
        ["headImg[" + i + "].fileName"]: data.path[i].name
      })

    }else{
      that.setData({
        ["headImg[" + i + "].fileName"]: that.generateTimeReqestNumber() + '.' + data.path[i].fileFormat
      })
    }

    obj.filename = data.path[i].fileName
    obj.time11 = data.path[i].time11
    obj.fileFormat = data.path[i].fileFormat

    var flage=-1 
    that.data.filemap.forEach((value,index)=>{
      var value = value

      // console.log(value[obj.fileFormat],111111111111111111111111111111)

      if (value[obj.fileFormat]){
        flage = index
      }
    })
    if (flage>-1){
      obj.fileType = that.data.filemap[flage][obj.fileFormat]
    }else{
      obj.fileType = 6
    }
    
    obj.per = 0
    obj.uploadTask=''

    obj.status=-1

    obj.path = data.path[i].path
    var jindulist = that.data.jindulist
    jindulist.push(obj)

    this.setData({
      jindulist: jindulist
    })

    var uploadTask = wx.uploadFile({
      url: data.url,
      filePath: data.path[i].path,
      name: 'file', //这里根据自己的实际情况改
      formData: {

        // userId: that.data.userId,
        parentId: that.data.thismuluid,
        fileName: data.path[i].fileName,

      }, //这里是上传图片时一起上传的数据
      header: { 
        "Content-Type": "multipart/form-data",
        "Authorization1": 'Bearer ' + wx.getStorageSync("token")
      },
      success(resU) {
        success++;
        that.setData({
          success:success
        })
        // console.log(resU)
        // if (JSON.parse(resU.data).error == 0) {
        //   wx.showToast({
        //     title: '上传成功,请到我的病历中查看！',
        //     icon: 'none',
        //     duration: 1000
        //   })
        // }
        var str = "jindulist[" + i + "].status"
        that.setData({
          [str]: true
        })
      },
      fail: (res) => {

        console.log(res)

        fail++; //图片上传失败，图片上传失败的变量+1
        that.setData({
          success: success
        })
        
     
        var str = "jindulist[" + i + "].status"
        that.setData({
          [str]: false
        })
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张            
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');

          console.log('成功：' + success + " 失败：" + fail)

          // return ('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数     
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })

    var str = "jindulist[" + i + "].uploadTask"
    that.setData({
      [str]: uploadTask
    })


    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)

      var str = "jindulist["+i+"].per"
      that.setData({
        [str]: res.progress
      })
      
    })

    
  },



  // chongxun
  chongxinshangchuan(e) {

    var index=e.currentTarget.dataset.index
    var that = this

    var str = "jindulist[" + index + "].status"
    that.setData({
      [str]: -1
    })

    var str = "jindulist[" + index + "].per"
    that.setData({
      [str]: 0
    })

    var str = "jindulist[" + index + "].uploadTask"
    that.setData({
      [str]: ''
    })

    

    var uploadTask1 = wx.uploadFile({
      url: src + '/applet/appletUploud',
      filePath: that.data.jindulist[index].path,
      name: 'file', //这里根据自己的实际情况改
      formData: {

        // userId: that.data.userId,
        parentId: that.data.thismuluid,
        fileName: that.data.jindulist[index].filename,

      }, //这里是上传图片时一起上传的数据
      header: { 
        "Content-Type": "multipart/form-data",
        "Authorization1": 'Bearer ' + wx.getStorageSync("token") 
      },
      success(resU) {
        success++;
       
        var str = "jindulist[" + index + "].status"
        that.setData({
          [str]: true
        })

      },
      fail: (res) => {

        console.log(res)

        var str = "jindulist[" + index + "].status"
        that.setData({
          [str]: false
        })
      },
      complete: () => {
       console.log("重新上传")
      }
    })

    var str = "jindulist[" + index + "].uploadTask"
    that.setData({
      [str]: uploadTask1
    })


    uploadTask1.onProgressUpdate((res) => {

      console.log('上传进度', res.progress)
      var str = "jindulist[" + index + "].per"
      that.setData({
        [str]: res.progress
      })

    })


  },

  quxiaoshangcuan(e){
    var index = e.currentTarget.dataset.index;

    console.log('quxiao')
    this.data.jindulist[index].uploadTask.offProgressUpdate(function () {
      console.log("取消监听了")
    })
    this.data.jindulist[index].uploadTask.abort()

   
  },


  // 选图片
  uploadimages: function () {

    var that = this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;

        var headImg = that.data.headImg;

        if (index == 0) {
          wx.chooseImage({
            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              console.log(tempFilePaths)


              for (let i = 0; i < tempFilePaths.length; i++) {
                var obj = {}
                obj.path = tempFilePaths[i]
                var time11 = that.generateTimeReqestNumber1()
                let fileNameqian = obj.path.split(".")//取到文件名开始到最后一个点的长度
                console.log(fileNameqian)
                let fileNameLength = fileNameqian.length;//取到文件名长度
                let fileFormat = fileNameqian[fileNameLength - 1]
                obj.fileFormat = fileFormat
                obj.time11 = time11
                obj.fileName = ''

                headImg.push(obj)
              }
              that.setData({
                headImg: headImg
              });

             

                that.uploadimg({
                  i: that.data.jindulist.length,
                  success: that.data.success,
                  fail: that.data.fail,

                  url: src + '/applet/appletUploud', //这里是你图片上传的接口
                  path: that.data.headImg //这里是选取的图片的地址数组        
                });

            }
          })
        } else if (index == 1) {
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片

              var headImg = that.data.headImg;

              const tempFilePaths = res.tempFilePaths;

              var obj = {}
              obj.path = tempFilePaths[0]

              var time11 = that.generateTimeReqestNumber1()
              let fileNameqian = obj.path.split(".")//取到文件名开始到最后一个点的长度
              console.log(fileNameqian)
              let fileNameLength = fileNameqian.length;//取到文件名长度
              let fileFormat = fileNameqian[fileNameLength - 1]
              obj.fileFormat = fileFormat
              obj.time11 = time11
              obj.fileName = ''

              headImg.push(obj)
              that.setData({
                headImg: headImg
              });
                that.uploadimg({
                  i: that.data.jindulist.length,
                  success: that.data.success,
                  fail: that.data.fail,

                  url: src + '/applet/appletUploud', //这里是你图片上传的接口
                  path: that.data.headImg //这里是选取的图片的地址数组        
                });
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },
  // 选视频
  uploadvideo: function () {
   
    var that = this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;

        var headImg = that.data.headImg;
        if (index == 0) {

          wx.chooseVideo({
            // count: num,
            maxDuration: 15,
            camera: 'back',

            sourceType: ['album'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePath;
              var obj = {}

              obj.path = tempFilePaths

            
              var time11 = that.generateTimeReqestNumber1()
              let fileNameqian = obj.path.split(".")//取到文件名开始到最后一个点的长度
              console.log(fileNameqian)
              let fileNameLength = fileNameqian.length;//取到文件名长度
              let fileFormat = fileNameqian[fileNameLength - 1]
              obj.fileFormat = fileFormat
              obj.time11 = time11
              obj.fileName = ''

           
              headImg.push(obj)
              that.setData({
                headImg: headImg
              });

                that.uploadimg({
                  i: that.data.jindulist.length,
                  success: that.data.success,
                  fail: that.data.fail,

                  url: src + '/applet/appletUploud', //这里是你图片上传的接口
                  path: that.data.headImg //这里是选取的图片的地址数组        
                });
            }
          })
        } else if (index == 1) {
          wx.chooseVideo({

            maxDuration: 15,
            camera: 'back',

            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片

              var headImg = that.data.headImg;

              const tempFilePaths = res.tempFilePath;

              var obj = {}
              obj.path = tempFilePaths

             
              var time11 = that.generateTimeReqestNumber1()
              let fileNameqian = obj.path.split(".")//取到文件名开始到最后一个点的长度
              console.log(fileNameqian)
              let fileNameLength = fileNameqian.length;//取到文件名长度
              let fileFormat = fileNameqian[fileNameLength - 1]
              obj.fileFormat = fileFormat
              obj.time11 = time11
              obj.fileName = ''

           
              headImg.push(obj)

              that.setData({
                headImg: headImg
              });

                that.uploadimg({
                  i: that.data.jindulist.length,
                  success: that.data.success,
                  fail: that.data.fail,

                  url: src + '/applet/appletUploud', //这里是你图片上传的接口
                  path: that.data.headImg //这里是选取的图片的地址数组        
                });
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },

  uploadwxwenjian: function () {

   
    var that = this
    wx.chooseMessageFile({
      count: 10,
      success(res) {
        
        var headImg = that.data.headImg;
        const tempFilePaths = res.tempFiles;
        console.log(tempFilePaths)


        for (let i = 0; i < tempFilePaths.length; i++) {
          var obj
          obj = tempFilePaths[i]
          headImg.push(obj)
        }
        that.setData({
          headImg: headImg
        });

        that.uploadimg({
          i: that.data.jindulist.length,
          success: that.data.success,
          fail: that.data.fail,

          url: src + '/applet/appletUploud', //这里是你图片上传的接口
          path: that.data.headImg //这里是选取的图片的地址数组        
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */ 
  pad2:function (n) { return n < 10 ? '0' + n : n },

  pad3: function (n) { 
    if (n < 10){
      return  '00' + n
    }
    if (n < 100){
      return '0' + n
    }
  },

  generateTimeReqestNumber: function() {
    var date = new Date();
    return date.getFullYear().toString() + this.pad2(date.getMonth() + 1) + this.pad2(date.getDate()) + this.pad2(date.getHours()) + this.pad2(date.getMinutes()) + this.pad2(date.getSeconds()) + this.pad2(date.getMilliseconds());
  },

  generateTimeReqestNumber1: function () {
    var date = new Date();
    return date.getFullYear().toString() + "-" + this.pad2(date.getMonth() + 1) + "-" + this.pad2(date.getDate()) + "  " + this.pad2(date.getHours()) + ":" + this.pad2(date.getMinutes()) 
  },

  onLoad: function (options) {
    

    var headImg = JSON.parse(options.headImg)
    var type = options.type
    var thismuluid = options.thismuluid

    console.log(headImg)

    headImg.forEach((vaule,index)=>{
      
      console.log(vaule.path,)

      var aa = vaule

      var time11 = this.generateTimeReqestNumber1()

      let fileNameqian = aa.path.split(".")//取到文件名开始到最后一个点的长度
      console.log(fileNameqian)

      let fileNameLength = fileNameqian.length;//取到文件名长度

      let fileFormat = fileNameqian[fileNameLength-1]

      aa.fileFormat = fileFormat
      aa.time11 = time11

      aa.fileName = ''

    })

    this.setData({
      thismuluid: thismuluid,
      headImg: headImg,
      type: type
    })


    if(type==0){
      wx.setNavigationBarTitle({
        title: '上传图片',
      })
    }
    if (type == 1) {
      wx.setNavigationBarTitle({
        title: '上传视频',
      })
    }
    if (type == 2) {
      wx.setNavigationBarTitle({
        title: '上传微信文件',
      })
    }


    this.uploadimg({
      url: src + '/applet/appletUploud', //这里是你图片上传的接口
      path: this.data.headImg //这里是选取的图片的地址数组        
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})